package com.it.springbootmybatis.controller;

import com.it.springbootmybatis.domain.Company;
import com.it.springbootmybatis.query.CompanyQuery;
import com.it.springbootmybatis.service.ICompanyService;
import com.it.springbootmybatis.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @projectName: springboot-practice
 * @package: com.it.springbootmybatis.controller
 * @className: CompanyService
 * @author: Navid
 * @description: TODO
 * @date: 2021/10/23 13:15
 * @version: 1.0
 */
@RestController
public class CompanyController {

    @Autowired
    private ICompanyService service;

    @Autowired
    StringRedisTemplate redisTemplate;

    @GetMapping("/list")
    public Map<String, Object> list() {
        Map<String, Object> map = new HashMap<>(10);
        List<Company> list = service.findAll();
        map.put("list", list);
        return map;
    }

    @GetMapping("/list-mapped")
    @ResponseBody
    public Result<List<Company>> listMapped() {
        List<Company> list = service.findAll();
        return Result.success(list);
    }

    @PostMapping("/insert")
    @ResponseBody
    public Result<String> insert(@RequestParam Company company) {
        service.insert(company);
        return Result.success("deleted successfully");
    }

    @PostMapping("/delete")
    public Result<String> delete(int id) {
        service.delete(id);
        return Result.success("deleted successfully");
    }

    @GetMapping("/list-query")
    public Result<List<Company>> queryPaged(String name, String addr, String contactName) {
        CompanyQuery companyQuery = new CompanyQuery();
        companyQuery.setCurrentPage(1);
        companyQuery.setPageSize(3);
        companyQuery.setName(name);
        companyQuery.setAddr(addr);
        companyQuery.setPersonCharged(contactName);
        List<Company> list = service.queryPaged(companyQuery);
        return Result.success(list);
    }

    @RequestMapping("/get-value-from-redis")
    public String getValueFromRedis(String key) {
        if (redisTemplate.hasKey(key)) {
            String value = redisTemplate.boundValueOps(key).get();
            return "取得数据为：" + value;
        } else {
            return "无此数据";
        }
    }
}
